<template>
  <el-container direction="vertical" style scoped>
    <Header />
    <el-row>
      <el-col :span="24" style="margin: auto">
        <el-steps :active="2">
          <el-step title="步骤 1" description="加入购物车"></el-step>
          <el-step title="步骤 2" description="生成订单"></el-step>
          <el-step title="步骤 3" description="支付"></el-step>
        </el-steps>
      </el-col>
    </el-row>
    <div style="width: 90%; border: 3px solid #f0f0f0; margin: auto">
      <el-row style="margin-left: 20px">
        <el-button type="text" @click="b()">新增收货地址</el-button>

        <el-dialog title="收货地址" :visible.sync="dialogFormVisible"><!-- 对话框 -->
          <el-form :model="form">
            <el-form-item label="收货人姓名" :label-width="formLabelWidth">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="收获人电话" :label-width="formLabelWidth">
              <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="收货人地址" :label-width="formLabelWidth">
              <el-input v-model="form.address" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="a">确 定</el-button>
          </div>
        </el-dialog>

        <h3>收件人信息:</h3>
        收货人：{{ checked.name }} &nbsp;&nbsp;&nbsp; 收货电话：{{
          checked.phone
        }}
        &nbsp;&nbsp;&nbsp; 收货地址：{{ checked.address }}
      </el-row>

      <el-row>
        <ul>
          <li
            v-for="(address, index) in addresses"
            :key="index"
            style="list-style: none"
          >
            <span
              class="bnt"
              style="display: inline-block; margin-top: 8px; margin-right: 10px"
            >
              <!-- 删除按钮 -->
              <el-button
                type="primary"
                icon="el-icon-delete"
                @click="deleteAddress(address)"
              ></el-button>
            </span>
            <el-radio-group v-model="checked" style="margin-top: 18px">
              <el-radio :label="address">
                <!--label="address" 是一个属性绑定语法，用于将一个变量或表达式的值绑定到 HTML 元素的 label 属性上。为每个表单组件提供一个唯一的标识值-->
                <span style="font-size: 18px"
                  >收货人：{{ address.name }}------收货电话：{{
                    address.phone
                  }}------ 收货地址：{{ address.address }}</span
                ></el-radio
              >
            </el-radio-group>
          </li>
        </ul>
      </el-row>
    </div>
    <el-row>
      <p>确认订单信息:</p>
    </el-row>
    <!-- 购物车表格 -->
    <el-row>
      <el-table :data="accounts">
        <!-- 商品名称 -->
        <el-table-column
          prop="name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <!-- 商品图片 -->
        <el-table-column prop="img" label="图片" align="center">
          <!-- template 标签来定义一个插槽，并将其命名为 slot-scope="scope"。这个插槽会被应用到自定义表格的某一列中 -->
          <template slot-scope="scope">
            <img
              :src="'http://127.0.0.1:3001/images/' + scope.row.img"
              alt=""
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <!-- 商品单价 -->
        <el-table-column prop="price" label="单价" align="center">
        </el-table-column>
        <!-- 商品数量 -->
        <el-table-column prop="num" label="数量" align="center">
        </el-table-column>
        <!-- 商品金额 -->
        <el-table-column prop="currency" label="金额" align="center">
          <template slot-scope="scope"> <!-- 定义作用域插槽 -->
            {{ scope.row.num * scope.row.price }}元
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="deleteItem(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <input type="checkbox" checked /> 号码保护
      （隐藏收件人真实手机号，保护隐私）
    </el-row>
    <el-row>
      实付款：<span style="color: red; font-size: 35px">￥{{ getTotal }}</span>
      &nbsp;
      <el-button type="success" @click="pay">去支付</el-button>
    </el-row>

    <br />
    <Footer />
  </el-container>
</template>

<script>
import Header from "../components/Header.vue";
import Footer from "../components/Footer.vue";
import { mapState } from "vuex";  //mapState 辅助函数，将state用户状态映射到组件的计算属性中
import { v4 as uuidv4 } from "uuid";

export default {
  components: {
    Header,
    Footer,
  },
  data() {
    return {
      accounts: [],
      orderId: "",
      dialogFormVisible: false,
      form: {
        name: "",
        phone: "",
        address: "",
        type: [],
      },
      formLabelWidth: "120px",
      addresses: "",
      checked: 1,
    };
  },
  computed: {
    ...mapState("user", ["user"]),
    getTotal() {
      let total = 0;
      if (this.user != null) {
        this.accounts.forEach((item) => {
          total += item.num * item.price;
        });
      }
      return total;
    },
  },

  methods: {
    deleteCartItems(cartid) {
      //删除购物车页面的商品数据
      this.axios
        .post("/api/carts/selectdel", { cartids: cartid }) //将cartid作为请求体中的cartids参数传递
        .then((res) => {
          console.log("已删除购物车选中商品数据");
          // this.$router.go(0);
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    a() {
      this.dialogFormVisible = false;
      let myaddress = {
        uid: this.user.uid,
        name: this.form.name,
        phone: this.form.phone,
        address: this.form.address,
      };
      this.axios
        .post("/api/accounts/addRess", {
          //insert写入用户地址信息
          myaddress: myaddress,
        })
        .then((response) => {
          console.log("成功发送请求");
          this.$router.go(0);
        })
        .catch((error) => {
          console.log("发送请求失败：", error);
        });
    },

    b() {
      this.dialogFormVisible = true;
      console.log(this.form);
    },
    // 删除商品
    deleteItem(item) {
      //findindex查找数组中满足提供的测试函数的第一个元素的索引
      const index = this.accounts.findIndex((account) => account === item); //index是商品在accounts数组中的索引
      if (index !== -1) {
        this.accounts.splice(index, 1);
      }
    },
    // 点击去结算，生成订单数据。
    pay() {
      let orderIds = []; // 添加一个数组来存储所有商品的订单ID
      let ordernum = uuidv4(); // 生成订单编号
      let uid = this.accounts[0].uid; // 假设所有商品都属于同一个用户
      let ordertime = new Date().toLocaleString(); // 下单时间
      let ordertotal = this.getTotal; // 订单总价
      this.axios
        .post("/api/accounts/addOrder", {
          // 请求体的内容
          ordernum: ordernum,
          uid: uid,
          ordertime: ordertime,
          orderstatus: "已下单",
          ordertotal: ordertotal,
          pricestatus: "未支付",
          sendoutGoods: "未发货",
          ReceivingStatus:"未收货",
        })
        .then((response) => {
          console.log("hhh:" + JSON.stringify(response.data)); //{"code":200,"message":"ok","data":{"orderid":169}}
          // (this.orderId = response.data.data.orderid),  //从响应中获取订单ID，并将其存储在this.orderId变量中
          //   orderIds.push(this.orderId); // 将订单ID添加到数组中
          // console.log("成功发送请求");

          const orderId = response.data.data.orderid; // 获取订单ID
          orderIds.push(orderId); // 将订单ID添加到数组中

          // 接下来插入订单详情
          // 创建一个数组存储所有的插入请求
          let detailPromises = this.accounts.map((item) => { //map=foreach遍历，返回一个数组（每个请求的 Promise），以便在 Promise.all 中处理。
            let detail = {
              orderid: orderId, // 使用刚刚插入的订单ID
              gid: item.gid, // 商品gid
              num: item.num, // 商品数量
              addressid: this.checked.addressid,
            };
            // 返回每个请求的Promise
            return this.axios
              .post("/api/accounts/addOrderDetail", detail) //detail对象作为请求体,通过axios发送到后端
              .then((response) => {
                this.deleteCartItems(item.cartid); // 删除购物车商品数据
                console.log("成功发送订单详情请求");
              })
              .catch((error) => {
                console.log("发送订单详情请求失败：", error);
              });
          });
         // 使用 Promise.all 来等待所有的订单详情插入请求完成，这样可以确保所有的商品都被正确插入到 ordersdetail 表中
          return Promise.all(detailPromises);
        })
        .then(() => {
          console.log("成功发送订单请求");
        })
        .catch((error) => {
          console.log("发送请求失败：", error);
        });
      // });
      setTimeout(() => {
        this.$router.push({
          path: "/pay",
          query: {
            orderTotal: this.getTotal,
            orderIds: JSON.stringify(orderIds), //query传参将选择的订单的id带去pay页面。
          },
        }); // 将订单ID数组转换为字符串并传递给支付页面
      }, 1000); // 延迟1秒以确保所有请求都已发送
    },
    deleteAddress(address) {
      this.axios
        .post("/api/accounts/adddel", { addressid: address.addressid }) //将address.addressid的值作为addressid发送到后台服务器
        .then((res) => {
          alert("你确定要删除吗？"); 
          this.$router.go(0);
        })
        .catch((err) => {
          alert(err.message);
        });
    },
  },

  // created 生命周期钩子函数，用于在组件创建时执行代码
  //  JSON.parse() 方法用于将 JSON 字符串转换为对应的 JavaScript 对象。
  created() {
    let datas = this.$route.query.data;
    console.log("datas:" + datas);
    this.accounts = JSON.parse(datas);

    let addid3 = {
      uid: this.user.uid,
    };
    this.axios
      .post("/api/accounts/addid", {
        //查询到此用户的所有地址信息
        addid2: addid3,
      })
      .then((response) => {
        console.log("成功读取数据");
        this.addresses = response.data.data.results5; // 将返回的数据赋值给addresses数组
        if (this.addresses.length > 0) {
          this.checked = this.addresses[0];
        }
      })
      .catch((error) => {
        console.log("读取数据失败：", error);
      });
  },
};
</script>

<style>
table {
  border: 1px solid #e9e9e9;
  border-collapse: collapse;
  border-spacing: 0;
}
th,
td {
  padding: 8px 16px;
  border: 1px solid #e9e9e9;
  width: 255px;
  text-align: center;
}
td {
  height: 80px;
}
th {
  background-color: #f7f7f7;
  color: #5c6b77;
  font-weight: 600;
}
</style>